//
//  QuestionDetailController.m
//  EcmDoctor
//
//  Created by 张进 on 15/6/16.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "QuestionDetailController.h"
#import "AppUtils.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <AVFoundation/AVFoundation.h>
#import "NetWorkUtil.h"
#import "UserAskPic.h"
#import <UIImageView+AFNetworking.h>
#import "DACircularProgressView.h"
#import "Treatmentsm.h"
#import "TreatmentsViewController.h"
#import "DoctorFreeInfo.h"
#import "BigImageViewController.h"
#import "DiagnoseChatController.h"
#import "KaiYaoViewController.h"
#import "OnlineModel.h"

@interface QuestionDetailController ()<AVAudioPlayerDelegate> {
    //问诊图片
    NSArray *askImages;
    int i;
    UIButton *btnPlayer;//播放按钮
    BOOL bl;
}

@property (nonatomic, strong) NSArray *dataAry;
@property(nonatomic,strong)AVAudioPlayer *player;
@property (nonatomic, strong) DACircularProgressView *voiceProgressView;//语音播放的圆环
@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, strong) UIButton *touchButton;
@property (nonatomic, strong) UILabel *lab;

@end

@implementation QuestionDetailController

@synthesize yzButton,yzButtonText,bqDescTitle,detailScrollView,name,sex,age,picUrls,voiceUrl,bqDesc,headIconUrl,headView;

-(IBAction)backClick:(id)sender{
    NSLog(@"alskdjflsdf");
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)yzClick:(id)sender{
    NSLog(@"yizhenClick...");
    //按钮文字颜色改变
//    [yzButtonText setTextColor:[UIColor colorWithRed:1.0 green:248.0/255 blue:238.0/255 alpha:1.0]];
    [yzButtonText setTextColor:[UIColor colorWithRed:1.0 green:0.8 blue:0.1 alpha:1.0]];
    yzButtonText.text = @"我要义诊";
    
//    NSLog(@"swidth:%f,sheight:%f",self.imgScrollView.frame.size.width,self.imgScrollView.frame.size.height);
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                              @"我要义诊" message:@"" delegate:self
                                             cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alertView show];
}

#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:
(NSInteger)buttonIndex{
    
    [yzButtonText setTextColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
    
    switch (buttonIndex) {
        case 0:
            NSLog(@"Cancel button clicked");
            break;
        case 1:
            NSLog(@"OK button clicked");
            
            [self performSegueWithIdentifier:@"segueCommunication" sender:self];
            
            
            break;
            
        default:
            break;
    }
    
}

-(void)changeToNavRootController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)tiaozhaun {
    NSLog(@"123");
    [self performSegueWithIdentifier:@"yiZhenTreatmentsLine" sender:_dataAry];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"yiZhenTreatmentsLine"]) {
        
        TreatmentsViewController *treatment = [segue destinationViewController];
        treatment.dataAry = sender;
        treatment.single = NO;
        if (_ifDownload) {
            treatment.i = _ifDownload;
        } else {
            treatment.i = _i;
        }
        
        
    } else if ([segue.identifier isEqualToString:@"toBigimage"]) {
        BigImageViewController *big = [segue destinationViewController];
        big.imageUrl = sender;
    }
    if([segue.identifier isEqualToString:@"segueCommunication"])
    {
        DiagnoseChatController *diac=segue.destinationViewController;
        diac.name= self.name;
        diac.age=self.age;
        diac.sex=self.sex;
        diac.headIconUrl=self.headIconUrl;
        NSLog(@"-------------%@",headIconUrl);
        diac.bqDesc=self.bqDesc;
        diac.user_info_id=self.user_info_id;
        diac.askId= self.askId;
    
    }
}


- (void)viewDidLoad {
//    [self.bqDesc sizeToFit];
    [super viewDidLoad];
    _dataAry = [NSArray array];
    
    // Do any additional setup after loading the view.
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"问题详情"];
    
    
    //左上角返回按钮
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
    
    //当没有数据时的提示
    _touchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [_touchButton addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
    
    _lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    _lab.center = CGPointMake(kScreenWidth/2, kScreenHeight/2);
    _lab.text = @"暂时没有义诊信息，点击刷新";
    _lab.textAlignment = NSTextAlignmentCenter;
    
    [self download];
    
}

- (void)download {
    
    if (_ifDownload) {
        [DoctorFreeInfo doctorFreeDetailWithaskId:_askId success:^(DoctorFreeInfo *doctor) {
            
//            DoctorFreeInfo *doctor = doctor;
            sex = doctor.sex;
            age = [NSString stringWithFormat:@"%d", doctor.age];
            name = doctor.name;
            headIconUrl = doctor.icon_Url;
            bqDesc = [NSString stringWithFormat:@"%@", doctor.content];
            voiceUrl = doctor.voiceUrl;
            picUrls = doctor.picUrl;
            _user_info_id = doctor.user_info_id;
            _askId = doctor.ask_info_id;
            
            [self creatUI];
            
            [_lab removeFromSuperview];
            [_touchButton removeFromSuperview];
            if (!doctor) {
                [self.view addSubview:_lab];
                [self.view addSubview:_touchButton];
            }
            
        } failure:^(NSError *error) {
            
        }];
        
        } else {
        
        [self creatUI];
    }
    
}

- (void)creatUI {
    //姓名，年龄，性别，头像
    self.nameLabel.text = name;
    self.sexLabel.text = sex;
    self.ageLabel.text = age;
    askImages = self.picUrls;
    
    if (_ifDownload == 2 || _ifDownload == 3 || _ifDownload == 4 || _i == 1) {
        [Treatmentsm requetDoctorpcWith:_doctorId And:_askId success:^(NSArray *treatmentsAry) {
            
            if (treatmentsAry.count == 0) {
                self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:@"治疗方案" withTarget:self action:@selector(tiaozhaun)];
            } else {
                self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:[NSString stringWithFormat:@"治疗方案(%lu)", (unsigned long)treatmentsAry.count] withTarget:self action:@selector(tiaozhaun)];
            }
            _dataAry = treatmentsAry;
        } failure:^(NSError *error) {
            
        }];
    
    } else if (_ifDownload == 1)
        yzButton.alpha = 0;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[NetWorkUtil getImagesBaseUrl],self.headIconUrl];
   
    NSURL *url = [NSURL URLWithString:urlStr];
    
    [self.headView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon"]];
    self.headView.clipsToBounds = YES;
    self.headView.layer.cornerRadius = headView.bounds.size.width/2;
    
    CGRect rect = self.view.frame;
    
    //按钮视图添加点击事件
    UITapGestureRecognizer*tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(yzClick:)];
    [yzButton addGestureRecognizer:tapGesture];
    
    double appWidth = [UIScreen mainScreen].applicationFrame.size.width;
    
    //"病情描述"标题
    bqDescTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 100, 20)];
//    if (_ifDownload) {
//        bqDescTitle.frame = CGRectMake(10, 5, 100, 20);
//    }
    bqDescTitle.text = @"病情描述:";
    [detailScrollView addSubview:bqDescTitle];
    CGRect bqRect = self.bqDescTitle.frame;
    double bqWidth =appWidth-bqRect.origin.x*2;
    
    //病情描述布局
    _labDetail = [[UILabel alloc] initWithFrame:CGRectMake(bqRect.origin.x, bqRect.origin.y+bqRect.size.height+15, bqWidth, 21)];
    _labDetail.font = [UIFont systemFontOfSize:14];
    _labDetail.numberOfLines = 10;
    _labDetail.text = bqDesc;
    [detailScrollView addSubview:_labDetail];
    [_labDetail sizeToFit];
    
    
    //播放音频按钮
    btnPlayer = [[UIButton alloc]initWithFrame:CGRectMake(rect.size.width/2-30, CGRectGetMaxY(_labDetail.frame)+15, 70, 70)];
    [btnPlayer addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnPlayer.tag = 10000;
    btnPlayer.layer.cornerRadius = 35;
    btnPlayer.clipsToBounds = YES;
    
    [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    
    //初始化语音圈
    self.voiceProgressView = [[DACircularProgressView alloc] initWithFrame:CGRectMake(rect.size.width/2-30, CGRectGetMaxY(_labDetail.frame)+15, 70, 70)];
    //声音播放进度条
    self.voiceProgressView.progressTintColor = [UIColor blackColor];
    self.voiceProgressView.trackTintColor = [UIColor lightGrayColor];
    self.voiceProgressView.progress = 0;
    self.voiceProgressView.borderWidth = 5;
    
    //判断是否有音频
    if (self.voiceUrl != nil && ![self.voiceUrl isEqualToString:@""]) {
        if (_player) {
            _player = nil;
        }
        [detailScrollView addSubview:self.voiceProgressView];
        [detailScrollView addSubview:btnPlayer];
    }
    
    //分割线
    UIView *splitLine = [[UIView alloc] init];
    
    if (self.voiceUrl != nil && ![self.voiceUrl isEqualToString:@""]) {
        splitLine.frame = CGRectMake(0, btnPlayer.frame.origin.y+btnPlayer.frame.size.height+20, appWidth, 0.5);
    } else {
        
        splitLine.frame = CGRectMake(0, _labDetail.frame.origin.y+_labDetail.frame.size.height+20, appWidth, 0.5);
    }
    
    splitLine.backgroundColor = [UIColor colorWithRed:241.0/255 green:224.0/255 blue:204.0/255 alpha:1.0];
    [detailScrollView addSubview:splitLine];
    
    //"患处照片"文字布局
    //"患处照片"文字布局
    UILabel *picTitle =[[UILabel alloc] initWithFrame:CGRectMake(bqRect.origin.x, splitLine.frame.origin.y+splitLine.frame.size.height+10, bqWidth, 21)];
    picTitle.numberOfLines = 1;
    picTitle.text = @"患处照片：";
    [picTitle setFont:[UIFont fontWithName:@"Helvetica" size:13]];
    if (picUrls.count != 0 && picUrls) {
        [detailScrollView addSubview:picTitle];
    }
    
    PagedFlowView *pageFlowView = [[PagedFlowView alloc] initWithFrame:CGRectMake(0, picTitle.frame.origin.y+picTitle.frame.size.height+10, appWidth, appWidth)];
    
    //    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.delegate = self;
    pageFlowView.minimumPageAlpha = 1;
    pageFlowView.minimumPageScale = 1;
    pageFlowView.backgroundColor = [UIColor colorWithRed:254.0/255 green:246.0/255 blue:233.0/255 alpha:1.0];
    
    if (self.picUrls.count != 0) {
        [detailScrollView addSubview:pageFlowView];
        //撑开上层“我要义诊”按钮位置
        UIView *btPlaceView = [[UIView alloc] initWithFrame:CGRectMake(0, pageFlowView.frame.origin.y+pageFlowView.frame.size.height, rect.size.width, 50)];
        if (!_ifDownload) {
            [detailScrollView addSubview:btPlaceView];
        }
        [detailScrollView addSubview:btPlaceView];
        [detailScrollView setContentSize:CGSizeMake(0, btPlaceView.frame.origin.y+btPlaceView.frame.size.height-50)];
    }
    
    if (_ifDownload == 2) {
        yzButtonText.text = @"继续义诊";
    } else if (_ifDownload == 3) {
        yzButtonText.text = @"查看义诊记录";
    }
    
    if (_ifDownload == 1) {
        
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 164, kScreenWidth, kScreenHeight-164)];
        scroll.backgroundColor = [UIColor colorWithRed:254.0/255 green:246.0/255 blue:233.0/255 alpha:1.0];
//        scroll.backgroundColor = [UIColor redColor];
        [self.view addSubview:scroll];
        [detailScrollView removeFromSuperview];
        [scroll addSubview:bqDescTitle];
        [scroll addSubview:_labDetail];
        //判断是否有音频
        if (self.voiceUrl != nil && ![self.voiceUrl isEqualToString:@""]) {
            if (_player) {
                _player = nil;
            }
            [scroll addSubview:btnPlayer];
            [scroll addSubview:_voiceProgressView];
            [scroll setContentSize:CGSizeMake(0, kScreenHeight-109+btnPlayer.bounds.size.height+15)];
        } else
            [scroll setContentSize:CGSizeMake(0, kScreenHeight-109)];
        
        [scroll addSubview:splitLine];
        if (picUrls.count != 0 && picUrls) {
            [scroll addSubview:picTitle];
            [scroll addSubview:pageFlowView];
        }
        [scroll setContentSize:CGSizeMake(0, kScreenHeight-163)];
    }
}



//-(void)alignTop:(UILabel *)label {
//    CGSize fontSize =[label.text sizeWithFont:label.font];
//    double finalHeight = fontSize.height *label.numberOfLines;
//    double finalWidth =label.frame.size.width;//expected width of label
//    CGSize theStringSize =[label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:label.lineBreakMode];
//    int newLinesToPad =(finalHeight - theStringSize.height)/ fontSize.height;
//    for(int i=0; i<newLinesToPad; i++)
//        label.text =[label.text stringByAppendingString:@"\n "];
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation


//#pragma PagedFlowViewDelegate implement
//- (void)flowView:(PagedFlowView *)flowView didScrollToPageAtIndex:(NSInteger)index{
//    
//}
//

- (void)flowView:(PagedFlowView *)flowView didTapPageAtIndex:(NSInteger)index{
    UserAskPic *askPic = [askImages objectAtIndex:index];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[NetWorkUtil getImagesBaseUrl],askPic.user_ask_pic];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    [self performSegueWithIdentifier:@"toBigimage" sender:url];
}

#pragma PagedFlowViewDataSource implement
- (NSInteger)numberOfPagesInFlowView:(PagedFlowView *)flowView{
    return askImages.count;
}

//返回给某列使用的View
- (UIView *)flowView:(PagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    UIImageView *imageView = [[UIImageView alloc]init];
    
    UserAskPic *askPic = [askImages objectAtIndex:index];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[NetWorkUtil getImagesBaseUrl],askPic.user_ask_pic];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    [imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon"]];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
//    [imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        
//        NSLog(@"%@", urlStr);
//        
//    }];
    
    
//        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",index+1]];
    
    return imageView;
}


//播放音频
- (void)buttonClicked:(UIButton *)btn {
    //本地路径
    NSString *myPath = [NSString stringWithFormat:@"%@/Documents/DataCache/%@",NSHomeDirectory(), [NSString stringWithFormat:@"https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/%@", self.voiceUrl]];
    bl = [[NSBundle mainBundle] pathForResource:myPath ofType:@""];
    
    //按钮的状态
    if (i == 0) {
        
        if (bl == NO) {//判断是否下载成功或有本地数据
            [self downloadVoice:myPath];
        } else {
            [self playVoice];
            [btnPlayer setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
            i = 1;
        }
        
    } else {
        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [_player pause];
        i = 0;
    }
}
//下载
- (void)downloadVoice:(NSString *)urlStr {
    
    //先下载到本地再播放
    [NetWorkUtil playerVoiceWithVoiceName:self.voiceUrl success:^(NSString *responseObject) {
        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
        i = 1;
        [self playVoice];
        
    } failure:^(NSError *error) {
        
    }];
        
}

- (void)playVoice {
    bl = YES;//成功下载后设置为yes
    
    //本地路径
    NSString *myPath = [NSString stringWithFormat:@"%@/Documents/DataCache/%@",NSHomeDirectory(), [NSString stringWithFormat:@"https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/%@", self.voiceUrl]];
    
    if (_player) {
        _player = nil;
    }
    
    //创建播放器
    //    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"song1.mp3" ofType:nil]] error:nil];
    _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:myPath] error:nil];
    [_player play];
    _player.delegate = self;
    
    //通过定时器使进度条与声音同步
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(audioPlayerChangeSlider:) userInfo:nil repeats:YES];
}

#pragma mark--AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
{
    i = 0;
    self.voiceProgressView.progress = 0;
    [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
}

-(void)audioPlayerChangeSlider:(NSTimer *)time{
    //进度条赋值 进度条长度为1
    self.voiceProgressView.progress = _player.currentTime/_player.duration;
    NSLog(@"%f", self.voiceProgressView.progress);
    if (_player.currentTime == _player.duration) {
        //        i = 0;
        //        [btnPlayer setBackgroundImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [time invalidate];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    //停止播放
    //停止定时器
    [_player stop];
    [_myTimer invalidate];
    
}

@end
